package sonet.textui;
import static ist.po.ui.Dialog.IO;
import ist.po.ui.Command;
import ist.po.ui.DialogException;
import java.io.*;
import sonet.*;
import sonet.textui.*;

public class Operations{

	public static void saveSocialNetwork(SocialNetwork sonet,String filename){
		SocialNetworkManager manager = new SocialNetworkManager();
		try{
			ObjectOutputStream o = new ObjectOutputStream(new BufferedOutputStream (new FileOutputStream(filename)));			
			try{
				manager.write(o,sonet);
			}
			finally{
				o.close();
			}			
		}	
		catch(InvalidClassException e){IO.println(e.getMessage());}
		catch(NotSerializableException e){IO.println(e.getMessage());}
		catch(IOException e){IO.println(e.getMessage());}	
	}
	
	
	/**
	 * @param args
	 */
	public static void loadSocialNetwork(BrowsingState state){
		SocialNetwork sonet = null;
		SocialNetworkManager m =new SocialNetworkManager();
		try{
			ObjectInputStream i = new ObjectInputStream( new BufferedInputStream ( new FileInputStream("sonet.dat")));
			try{
				sonet = m.read(i);
			}
			finally{
				i.close();
			}			 
		}	
		catch(ClassNotFoundException e){
			IO.println( e.getMessage());
		}
		catch(InvalidClassException e){
			IO.println( e.getMessage());
		}
		catch(StreamCorruptedException e){
			IO.println( e.getMessage());
		}
		catch(OptionalDataException e){
			IO.println( e.getMessage());
		}
		catch(IOException e){
			IO.println( e.getMessage());
		}
		catch(Exception e){
			IO.println( e.getMessage());
		}
		
		if( sonet == null){
			sonet = new SocialNetwork();
		}	
		state.sonet = sonet;
	}
	
	/** 
		@param state . state.sonet is initialized with a non null SocialNetwork instance
	*/
	public static Agent requestAgent(BrowsingState state,String message){
		int id=0;
		Agent user =null;
		
		try{			
			id = IO.readInteger( message );
			while( (user = state.sonet.getAgent(id)) == null){
				id = IO.readInteger( message);
			}		
		
		}
		catch(IOException e){
			IO.println(e.getMessage());
		}
		
		return user;	
	}
	
	public static void createAgent(String[] fields,SocialNetwork sonet)throws Exception{
		int id = Integer.parseInt(fields[1]);
		String name = fields[2];
		String email = fields[3];
		String phone = fields[4];
		Agent a;
		if( fields[0].equals("PERSON")){ 
			a = new Individual(id,name,email,phone);
		}
		else if( fields[0].equals("ORGANIZATION")){
			a = new Organization(id,name,email,phone);
		}
		else{
			throw new Exception("createAgent:unknown type");
		}
		sonet.addAgent(a);		
	}
	
	public static void createMessage(String[] fields,SocialNetwork sonet)throws Exception{
		int id = Integer.parseInt(fields[1]);
		int from = Integer.parseInt(fields[2]);
		int to = Integer.parseInt(fields[3]);
		String subject = fields[4];
		String body = fields[5];
		Agent fromAgent = sonet.getAgent(from);
		Agent toAgent = sonet.getAgent(to);
		Message m = new Message(id,fromAgent,toAgent,subject,body);		
		if( fromAgent == null){
			throw new Exception("createMessage:fromAgent=null");
		}
		if( toAgent == null){
			throw new Exception("createMessage:toAgent=null");
		}
		fromAgent.messageSent(m);
		toAgent.messageReceived(m);
		sonet.addMessage(m);		
	}
	
	public static void createPublication(String[] fields,SocialNetwork sonet)throws Exception{
		int id = Integer.parseInt(fields[1]);
		int owner = Integer.parseInt(fields[2]);
		String description = fields[3];
		String content = fields[4];
		Publication p;
		if( fields[0].equals("NOTE") ){
			p = new Note(id,owner,description,content);	
		}
		else if( fields[0].equals("IMAGE")){
			p = new Image(id,owner,description,content);
		}
		else if( fields[0].equals("URI")){
			p = new URL(id,owner,description,content);
		}
		else{
			throw new Exception("createPublication:unknown type");
		}
		Agent agent = sonet.getAgent(owner);
		if( agent == null){
			throw new Exception("createPublication:agent=null:"+owner);
		}
		agent.registPublication(p);
		sonet.addPublication(p);		
	}

	public static void createConnection(String[] fields,SocialNetwork sonet)throws Exception{
		int id1 = Integer.parseInt(fields[1]);
		int id2 = Integer.parseInt(fields[2]);
		boolean id1Accepting = Boolean.parseBoolean(fields[3]);
		boolean id2Accepting = Boolean.parseBoolean(fields[4]);
		Agent agent1 = sonet.getAgent(id1);
		Agent agent2 = sonet.getAgent(id2);
		ConnectionStatus status1 = id1Accepting? ConnectionStatus.OPEN:ConnectionStatus.CLOSED;
		ConnectionStatus status2 = id2Accepting? ConnectionStatus.OPEN:ConnectionStatus.CLOSED;
		if( agent1 == null){
			throw new Exception("createMessage:agent1=null");
		}
		if( agent2 == null){
			throw new Exception("createMessage:agent2=null");
		}		
		Connection c = new Connection(agent1,agent2,status1,status2);
		agent1.connectionEstablished(c);
		agent2.connectionEstablished(c);	
	}
	
	public static void createEntity(String line,SocialNetwork sonet) throws Exception{
		String dados[] = line.split("\\|");
		if( dados[0].equals("PERSON") || dados[0].equals("ORGANIZATION")){
			createAgent(dados, sonet);
		}
		else if( dados[0].equals("MESSAGE")){
			createMessage(dados, sonet);
		}
		else if( dados[0].equals("NOTE") || dados[0].equals("IMAGE") || dados[0].equals("URI")){
			createPublication(dados, sonet);
		}
		else if( dados[0].equals("CONNECTION")){
			createConnection(dados, sonet);
		}
		else{
			for(String s : dados){
				IO.println(s);
			}
			throw new Exception("createEntity: unknown entity:" + line);
		}
		
	}
	
	public static void readTextInput(BufferedReader r, SocialNetwork sonet)throws Exception{
		String line;
		while( (line = r.readLine()) != null){
			try{
				createEntity(line,sonet);
			}
			catch(Exception e){
				throw new Exception("readTextInput:" + e.getMessage());
			}
		}
	}
	
	public static void loadSocialNetworkFromTextInput(BrowsingState state){
		state.sonet = new SocialNetwork();
		
		String file = System.getProperty("Import");		
		if( file != null){
			try{
				BufferedReader r = new BufferedReader(new FileReader(file));
				try{
					readTextInput(r,state.sonet);
				}
				finally{
					r.close();
				}
			}
			catch(IOException e){
				IO.println(e.getMessage());
			}
			catch(Exception e){
				IO.println(e.getMessage());
			}
		}	
	}


	
}